<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------

namespace think\queue\connector;

use Closure;
use Exception;

class RedisCluster extends Redis
{

    public function __construct(\RedisCluster $redis, $default = 'default', $retryAfter = 60, $blockFor = null)
    {
        $this->redis      = $redis;
        $this->default    = $default;
        $this->retryAfter = $retryAfter;
        $this->blockFor   = $blockFor;
    }

    public static function __make($config)
    {
        if (extension_loaded('redis')) {
            $auth = null;
            if ('' != $config['password']) {
                $auth = $config['password'];
            }

            $serverList = $config['host'];


            $redis = new \RedisCluster(null, $serverList, $config['timeout'], null,$config['persistent'], $auth);

            return new self($redis, $config['queue'], $config['retry_after'] ?? 60, $config['block_for'] ?? null);

        } else {
            throw new \BadFunctionCallException('not support: redis');
        }
        throw new Exception('redis扩展未安装');
    }

    /**
     * 移动延迟任务
     *
     * @param string $from
     * @param string $to
     * @param bool   $attempt
     */
    public function migrateExpiredJobs($from, $to, $attempt = true)
    {

        $jobs = $this->redis->zRangeByScore($from, '-inf', $this->currentTime());

        if (!empty($jobs)) {
            $res = $this->redis->zRemRangeByRank($from, 0, count($jobs) - 1);

            if($res){
                for ($i = 0; $i < count($jobs); $i += 100) {

                    $values = array_slice($jobs, $i, 100);

                    $this->redis->rPush($to, ...$values);
                    
                }
            }
        }
    }

}
